package demo.fallback;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import com.netflix.hystrix.exception.HystrixTimeoutException;

@Component
public class CustomerServiceFallbackProvider implements FallbackProvider {

	@Override
	public String getRoute() {
		return "customer-service"; 
	}

	@Override
	public ClientHttpResponse fallbackResponse(String route, final Throwable cause) {
		
		HttpStatus httpStatus;
		if (cause instanceof HystrixTimeoutException) {
			httpStatus = HttpStatus.GATEWAY_TIMEOUT;
        } else {
        	httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
        }
		
		 return new ClientHttpResponse() {
	            @Override
	            public HttpStatus getStatusCode() throws IOException {
	                return httpStatus;
	            }

	            @Override
	            public int getRawStatusCode() throws IOException {
	                return httpStatus.value();
	            }

	            @Override
	            public String getStatusText() throws IOException {
	                return httpStatus.getReasonPhrase();
	            }

	            @Override
	            public void close() {

	            }

	            @Override
	            public InputStream getBody() throws IOException {
	                return new ByteArrayInputStream("customer-service is unavailable".getBytes());
	            }

	            @Override
	            public HttpHeaders getHeaders() {
	                HttpHeaders headers = new HttpHeaders();
	                headers.setContentType(MediaType.APPLICATION_JSON);
	                return headers;
	            }
	        };
	}

}
